package com.rainy.generator.controller;

import com.rainy.generator.common.util.ResultUtil;
import com.rainy.generator.entity.PathEntity;
import com.rainy.generator.entity.PathQuery;
import com.rainy.generator.entity.TableQuery;
import com.rainy.generator.service.PathService;
import com.rainy.generator.service.TableService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;

/**
 * @author liuqin on 2017/12/16
 */
@RequestMapping("/path")
@Controller
public class PathController {
    @Resource
    private PathService pathService;
    @Resource
    private TableService tableService;

    @ResponseBody
    @RequestMapping(value = "list",method = RequestMethod.GET)
    public Object list(String dbName,Long page,Long limit){
        PathQuery pathQuery = new PathQuery();
        pathQuery.setDbName(dbName);
        if (page!=null && limit!=null){
            pathQuery.setOffset((page - 1) * limit);
            pathQuery.setLimit(limit);
        }
        return ResultUtil.toJsonResult(pathService.queryPaths(pathQuery),pathService.queryCount(pathQuery));
    }

    @RequestMapping("")
    public Object list(ModelMap modelMap,String dbName){
        modelMap.put("dbs",tableService.queryDataBases());
        if (StringUtils.isNotBlank(dbName)) {
            modelMap.put("dbName", dbName);
        }
        return "path";
    }

    @RequestMapping("toEdit")
    public Object toEdit(ModelMap modelMap,Long id,String dbName){
        PathEntity  pathEntity = new PathEntity();
        if (id!=null){
            pathEntity = pathService.queryPathById(id);
        }
        if (StringUtils.isNotBlank(dbName)) {
            pathEntity.setDb(dbName);
        }

        if (StringUtils.isBlank(pathEntity.getDb())){
            pathEntity.setDb(tableService.getConnectDb());
        }
        modelMap.put("connectDb",tableService.getConnectDb());
        modelMap.put("path",pathEntity);
        modelMap.put("dbs",tableService.queryDataBases());
        return "path-edit";
    }

    @ResponseBody
    @RequestMapping("edit")
    public Object edit(PathEntity pathEntity){
        if (pathEntity.getId()!=null) {
            pathService.update(pathEntity);
        }else{
            pathService.save(pathEntity);
        }
        return ResultUtil.toJsonSuccResult("成功！");
    }

    @ResponseBody
    @RequestMapping("save")
    public Object save(PathEntity pathEntity){
        pathService.save(pathEntity);
        return ResultUtil.toJsonSuccResult("成功！");
    }

    @ResponseBody
    @RequestMapping("delete")
    public Object delete(Long id){
        pathService.delete(id);
        return ResultUtil.toJsonSuccResult("成功！");
    }
}
